<template>
  <el-upload :class="{ 'disabled': disabled }" list-type="picture-card" action="#" :http-request="httpRequest"
    :on-preview="seeBigImg" :on-remove="removeImg" v-model:file-list="fileList" :limit="limit">
    <el-icon>
      <Plus />
    </el-icon>
  </el-upload>
  <!-- 查看大图 -->
  <el-dialog v-model="isSeeImg" title="预览" append-to-body width="40%" @close="dialogImageUrl = ''">
    <img style="width: 100%;" :src="dialogImageUrl" />
  </el-dialog>
</template>

<script setup>

import { defineProps, computed, ref, watch } from 'vue'
import { upImgApi } from '@/api/common/index.js'

const props = defineProps({
  imgUrl: String,
  limit: {
    type: Number,
    default: 1,
  }
})
const isSeeImg = ref(false)
const dialogImageUrl = ref('')
const fileList = ref([])
const emit = defineEmits(['update:imgUrl'])
// 判断是否大于最大数量
const disabled = computed(() => {
  return (props.imgUrl ? props.imgUrl.split(",").length : 0) >= props.limit;
})
watch(() => props.imgUrl, (val) => {
  // console.log(val);
  fileList.value = props.imgUrl ? props.imgUrl.split(',').map(item => ({
    url: import.meta.env.VITE_APP_BASE_IMG + item,
    upUrl: item
  })) : []
}, { immediate: true })

watch(fileList, (val) => {
  // console.log(val);
  emit('update:imgUrl', val ? val.map(item => item.upUrl).join(',') : '')
}, { deep: true, immediate: true })


// 自定义上传图片
const httpRequest = async ({ file }) => {
  // console.log(fileList.value);
  let fd = new FormData();
  fd.append("file", file);
  const { data: { url } } = await upImgApi(fd);
  // console.log(url);
  fileList.value[fileList.value.length - 1].upUrl = url
}

// 图片移除时的钩子
const removeImg = ({ uid }) => {
  // console.log(uid);
  fileList.value = fileList.value.filter((item) => item.uid !== uid);

}
// 点击当前图片触发的钩子
const seeBigImg = (file) => {
  // console.log("--------", file);
  dialogImageUrl.value = file.url;
  // console.log(dialogImageUrl);
  isSeeImg.value = true;
}

</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep .el-upload {
    display: none;
  }
}
</style>